package com.aaa.train.controller;


import com.aaa.common.entity.ResultData;
import com.aaa.common.entity.TbFiles;

import com.aaa.train.service.TbFilesService;
import org.apache.commons.io.FilenameUtils;

import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.soap.Addressing;
import java.io.File;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wang
 * @since 2020-08-14
 */
@Controller
@RequestMapping("/tbFiles")
public class TbFilesController {
    @Addressing
    private TbFilesService tbFilesService;
    @ResponseBody
    @RequestMapping("selectFiles")
    public List<TbFiles> selectFiles(){

        return tbFilesService.selectList(null);
    }

    @ResponseBody
    @RequestMapping("insertFiles")
    public ResultData insertFiles(MultipartFile aaa){
        try {
            //获取文件原始名称
        String oldFileName = aaa.getOriginalFilename();
        //获取文件后缀
        String extension = "."+ FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss")+ UUID.randomUUID().toString().replace("-","")+extension;
        //文件大小
        long size = aaa.getSize();
        //文件类型
        String type = aaa.getContentType();
        //处理根据时间生成目录

            String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dateDirPath = "E:/图片上传/"  + dateFormat;

            File dateDir = new File(dateDirPath);
            if (!dateDir.exists())dateDir.mkdir();
            //处理文件上传
           aaa.transferTo(new File(dateDir,newFileName));
           TbFiles tbFiles = new TbFiles();
           tbFiles.setOldFileName(oldFileName);
           tbFiles.setNewFileName(newFileName);
           tbFiles.setExt(extension);
           tbFiles.setPath(dateDirPath);
           tbFiles.setSize(size);
           tbFiles.setDowncounts(0);
           tbFiles.setUploadTime(new Date().toString());
           tbFilesService.insert(tbFiles);
            JSONObject resUrl = new JSONObject();
            resUrl.put("src",dateDirPath);
            return new ResultData(true,"上传成功",resUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

